//
//  DownLoadViewController.m
//  WULIHH
//
//  Created by tang on 16/4/22.
//  Copyright © 2016年 tang. All rights reserved.
//

#import "DownLoadViewController.h"
#import "Header.h"
#import "AFNetworking.h"
#import "MJRefresh.h"

#import "WuLiRequestTypeStarAPI.h"
//#import "SUcaiViewController.h"

#import "TypeWorkCollectionViewCell.h"


#import "DataBaseBoxImageModel.h"


#import "LookUseImageViewController.h"

@interface DownLoadViewController ()<UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, TypeWorkCollectionViewCellDelegate>
{
    UICollectionView *mainCollectionView;
    NSMutableArray *dataMutableArray;
    NSDictionary *infoDic;
    
    NSMutableArray *IDMutableArray;
    
    
    UILabel *SucaiTitle;
    
    NSString *pageString;
//    SUcaiViewController *sucaiController;
}

@end

@implementation DownLoadViewController


- (void)loadView
{
    [super loadView];
    [self.view setBackgroundColor:uicolor(237, 237, 237)];
    
    dataMutableArray = [NSMutableArray new];
    IDMutableArray = [NSMutableArray new];
    
    pageString = @"1";
    
    //设置底色
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WithView, 64.0)];
    [self.view addSubview:backView];
    [backView setBackgroundColor:uicolor(253, 202,47)];
    
    SucaiTitle = [[UILabel alloc] initWithFrame:CGRectMake(WithView / 2.0 - 50, 26.0, 100, 30)];
    [SucaiTitle setText:_titleNameStr];
    [SucaiTitle setFont:[UIFont systemFontOfSize:16.0]];
    [SucaiTitle setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:SucaiTitle];

    
    UIImage *image = nil;
    image = [UIImage imageNamed:@"Detalback.png"];
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 32, 10, 18)];
    [backButton setBackgroundImage:image forState:UIControlStateNormal];
    [self.view addSubview:backButton];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(backButton.frame)+6, 31.0, 50.0, 20.0)];
    [lable setText:@"返回"];
    [lable setFont:[UIFont systemFontOfSize:15.0]];
    [lable setTextAlignment:NSTextAlignmentLeft];
    [self.view addSubview:lable];
    
    UIButton *back = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 90, 90)];
    [self.view addSubview:back];
    [back addTarget:self action:@selector(popTOVIEW) forControlEvents:UIControlEventTouchUpInside];

    
    
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    mainCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, WithView, heightView-64.0) collectionViewLayout:flowLayout];
    [mainCollectionView setBackgroundColor:uicolor(221, 221, 221)];
    [self.view addSubview:mainCollectionView];

    [[DataBaseBoxImageModel sharedInstance] openDataBase];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [mainCollectionView setDelegate:self];
    [mainCollectionView setDataSource:self];
    
    [mainCollectionView registerClass:[TypeWorkCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(typeWorkImageGetBack:) name:@"typework" object:nil];
    
    [[DataBaseBoxImageModel sharedInstance] readDownLoadImageID:^(NSArray *IDArrya){
    
//        NSLog(@"%@", IDArrya);
        [IDMutableArray addObjectsFromArray:IDArrya];
    }];
    
    mainCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewMyWorkioData)];
    mainCollectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreMyWorkioData)];
    [mainCollectionView.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tabBarController setHidesBottomBarWhenPushed:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)popTOVIEW
{
    [self.navigationController popViewControllerAnimated:YES];
}



//刷新
- (void)loadNewMyWorkioData
{
    [WuLiRequestTypeStarAPI requestStarType:_StarID withTags:_tagsID withPage:pageString];
}


//加载
- (void)loadMoreMyWorkioData
{
    pageString = [NSString stringWithFormat:@"%d", [pageString intValue] + 1];
    [WuLiRequestTypeStarAPI requestStarType:_StarID withTags:_tagsID withPage:pageString];
}

//图片数据返回
- (void)typeWorkImageGetBack:(NSNotification *)notion
{
    [mainCollectionView.mj_header endRefreshing];
    [mainCollectionView.mj_footer endRefreshing];
    infoDic = [notion userInfo];
    if ([[infoDic valueForKey:@"success"] intValue] == 1)
    {
        if ([pageString isEqualToString:@"1"])
        {
            [dataMutableArray removeAllObjects];
        }
        else
        {
            if ([[infoDic valueForKey:@"data"] count] == 0)
            {
                pageString = [NSString stringWithFormat:@"%d", [pageString intValue] - 1];
            }
        }
        
        
        [dataMutableArray addObjectsFromArray:[infoDic valueForKey:@"data"]];
        [mainCollectionView reloadData];
    }
    else
    {
        
    }
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return dataMutableArray.count;
}


//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"cell";
    TypeWorkCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
//    [cell setTag:indexPath.row];
    [cell setTag:indexPath.row];
    [cell setMTypeWorkCollectionViewCellDelegate:self];
    [cell setModelWithFavImage:dataMutableArray[indexPath.row] withIDArray:IDMutableArray];
    return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout

//定义每个Item 的大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(biliwith(147.0), biliwith(118.0));
}
//
////定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 5, 0, 5);
}
//
//
//
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 9.0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 6.0;
}



#pragma mark---下载图片
- (void)downLoadImage:(NSString *)imageIDString
{
    int i = [imageIDString intValue];
    
//    NSLog(@"%@", dataMutableArray[i]);
//    NSDictionary *dic = dataMutableArray[i];
    
    [dataMutableArray[i] setValue:@"1" forKey:@"isCollected"];
    
    NSString *connect = [NSString stringWithFormat:@"%@", [dataMutableArray[i] valueForKey:@"id"]];
    
    [WuLiRequestTypeStarAPI requestFavImageWith:connect];
    dispatch_queue_t network_queue;
    
    network_queue = dispatch_queue_create("com.myapp.network", nil);
    
    
    dispatch_async(network_queue, ^{
        
        
        NSData *dada = [NSData dataWithContentsOfURL:[NSURL URLWithString:[dataMutableArray[i] valueForKey:@"origImageUrl"]]];
        [[DataBaseBoxImageModel sharedInstance] writeImageWithConnectID:connect withImageData:dada];
        // 回到主线程
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 显示图片到界面
            
    
        });
        
        
        
    } );
}






//进入查看引用
- (void)pushUseIMageViewWithTag:(NSInteger)tag
{
//    NSLog(@"%@", dataMutableArray[tag]);
    LookUseImageViewController *lookUseView = [[LookUseImageViewController alloc] init];
    lookUseView.imageIDString = [[dataMutableArray objectAtIndex:tag] valueForKey:@"id"];
    [self.navigationController pushViewController:lookUseView animated:YES];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
